package com.clothes.aweiDoExercises.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clothes.aweiDoExercises.common.ErrorCode;
import com.clothes.aweiDoExercises.constant.CommonConstant;
import com.clothes.aweiDoExercises.exception.BusinessException;
import com.clothes.aweiDoExercises.exception.ThrowUtils;
import com.clothes.aweiDoExercises.mapper.QuestionBankQuestionMapper;
import com.clothes.aweiDoExercises.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.clothes.aweiDoExercises.model.entity.Question;
import com.clothes.aweiDoExercises.model.entity.QuestionBank;
import com.clothes.aweiDoExercises.model.entity.QuestionBankQuestion;
import com.clothes.aweiDoExercises.model.entity.User;
import com.clothes.aweiDoExercises.model.vo.QuestionBankQuestionVO;
import com.clothes.aweiDoExercises.model.vo.UserVO;
import com.clothes.aweiDoExercises.service.QuestionBankQuestionService;
import com.clothes.aweiDoExercises.service.QuestionBankService;
import com.clothes.aweiDoExercises.service.QuestionService;
import com.clothes.aweiDoExercises.service.UserService;
import com.clothes.aweiDoExercises.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 题库题目关联表服务实现
 *
 * @author <<a href="www.yclothes.top">阿伟智能面试刷题平台</a>">clothes</a>
 * @from <a href="https://www.code-nav.cn">阿伟智能刷题学习平台</a>
 */
@Service
@Slf4j
public class QuestionBankQuestionServiceImpl extends ServiceImpl<QuestionBankQuestionMapper, QuestionBankQuestion> implements QuestionBankQuestionService {

    @Resource
    private UserService userService;
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionBankService questionBankService;
    /**
     * 校验数据
     *
     * @param questionBankQuestion
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validQuestionBankQuestion(QuestionBankQuestion questionBankQuestion, boolean add) {
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.PARAMS_ERROR);
        //题目和题库必须存在
        Long questionId = questionBankQuestion.getQuestionId();//题目id
        if (questionId!=null){
            Question question = questionService.getById(questionId);
            ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        Long questionBankId = questionBankQuestion.getQuestionBankId();//题库id
        if (questionBankId!=null){
            QuestionBank questionBank = questionBankService.getById(questionBankId);
            ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不存在");
        }

        //不需要校验
/*        // todo 从对象中取值
        String title = questionBankQuestion.getTitle();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }*/
    }

    /**
     * 获取查询条件
     *
     * @param questionBankQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionBankQuestion> getQueryWrapper(QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest) {
        QueryWrapper<QuestionBankQuestion> queryWrapper = new QueryWrapper<>();
        if (questionBankQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionBankQuestionQueryRequest.getId();
        Long notId = questionBankQuestionQueryRequest.getNotId();
        String sortField = questionBankQuestionQueryRequest.getSortField();
        String sortOrder = questionBankQuestionQueryRequest.getSortOrder();
        Long questionBankId = questionBankQuestionQueryRequest.getQuestionBankId();
        Long questionId = questionBankQuestionQueryRequest.getQuestionId();
        Long userId =questionBankQuestionQueryRequest.getUserId();

        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionBankId), "questionBankId", questionBankId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题库题目关联表封装
     *
     * @param questionBankQuestion
     * @param request
     * @return
     */
    @Override
    public QuestionBankQuestionVO getQuestionBankQuestionVO(QuestionBankQuestion questionBankQuestion, HttpServletRequest request) {
        // 对象转封装类
        QuestionBankQuestionVO questionBankQuestionVO = QuestionBankQuestionVO.objToVo(questionBankQuestion);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = questionBankQuestion.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionBankQuestionVO.setUser(userVO);
        // endregion

        return questionBankQuestionVO;
    }

    /**
     * 分页获取题库题目关联表封装
     *
     * @param questionBankQuestionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionBankQuestionVO> getQuestionBankQuestionVOPage(Page<QuestionBankQuestion> questionBankQuestionPage, HttpServletRequest request) {
        List<QuestionBankQuestion> questionBankQuestionList = questionBankQuestionPage.getRecords();
        Page<QuestionBankQuestionVO> questionBankQuestionVOPage = new Page<>(questionBankQuestionPage.getCurrent(), questionBankQuestionPage.getSize(), questionBankQuestionPage.getTotal());
        if (CollUtil.isEmpty(questionBankQuestionList)) {
            return questionBankQuestionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionBankQuestionVO> questionBankQuestionVOList = questionBankQuestionList.stream().map(questionBankQuestion -> {
            return QuestionBankQuestionVO.objToVo(questionBankQuestion);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankQuestionList.stream().map(QuestionBankQuestion::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        questionBankQuestionVOList.forEach(questionBankQuestionVO -> {
            Long userId = questionBankQuestionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionBankQuestionVO.setUser(userService.getUserVO(user));
        });
        // endregion

        questionBankQuestionVOPage.setRecords(questionBankQuestionVOList);
        return questionBankQuestionVOPage;
    }

    /**
     * 批量添加题目到题库
     * @param questionIdList 题目id列表
     * @param questionBankId 题库id
     * @param loginUser 用户信息
     */
    @Override
    @Async
    public void batchAddQuestionsToBank(List<Long> questionIdList, Long questionBankId, User loginUser) {
        //参数校验
        //检查题目id列表不能为空
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIdList),ErrorCode.PARAMS_ERROR,"题目id列表不能为空");
        //检查题库id不能为负数
        ThrowUtils.throwIf(questionBankId<=0,ErrorCode.PARAMS_ERROR,"题库 id 非法");
        //检查用户是否登录
        ThrowUtils.throwIf(loginUser==null,ErrorCode.NOT_LOGIN_ERROR);//未登录账号不允许进行操作

        //根据题目id列表查询题目列表,过滤掉不存在的题目
        LambdaQueryWrapper<Question> questionLambdaQueryWrapper = Wrappers.lambdaQuery(Question.class)
                .select(Question::getId)
                .in(Question::getId, questionIdList);

        //然后根据获取到的题目列表把合法的题目id进行封装
        List<Long> validQuestionIdList = questionService.listObjs(questionLambdaQueryWrapper, obj -> (Long) obj);
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList),ErrorCode.NOT_FOUND_ERROR,"合法的题目列表为空");

        //检查那些题目已经在题库中
        LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                .eq(QuestionBankQuestion::getQuestionBankId, questionBankId) //查询给定的题库id中的题目
                .in(QuestionBankQuestion::getQuestionId, validQuestionIdList);//查询给定的题库id中的题目
        //查询出来的结果是有效题目列表
        List<QuestionBankQuestion> existsQuestionList = this.list(lambdaQueryWrapper);
        //获取已经在题目中的题目id集合,通过后续的处理,避免重复添加
        Set<Long> existsQuestionIdSet = existsQuestionList.stream()
                .map(QuestionBankQuestion::getQuestionId)
                .collect(Collectors.toSet());
        //进行过滤,已经存在于题库中的题目就不需要添加了
        validQuestionIdList = validQuestionIdList.stream().filter(questionId -> {
            return !existsQuestionIdSet.contains(questionId);
        }).collect(Collectors.toList());

        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList),ErrorCode.PARAMS_ERROR,"所有的题目都在题库中");

        //再进行检查看一下合法的题目id是否为空
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList),ErrorCode.NOT_FOUND_ERROR,"题目不存在");

        //自定义线程池(io密集型线程池)
        ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
                20, //线程池中线程数量
                50, //线程池中线程最大数量
                60L, //线程池中空闲线程存活时间
                TimeUnit.SECONDS, //线程池中空闲线程存活时间单位
                new LinkedBlockingQueue<>(10000), //现成阻塞队列容量
                new ThreadPoolExecutor.CallerRunsPolicy() //拒绝策略: 由调用者线程来执行该任务
        );

        //创建一个数组用来保存批次任务
        List<CompletableFuture<Void>> futures = new ArrayList<>();


        //分批处理避免长事务,假设每次处理1000条数据
        int batchSize = 1000; //每次处理的条数
        int totalQuestionListSize = validQuestionIdList.size(); //有效题目数量

        for (int i = 0; i < totalQuestionListSize; i+=batchSize) {
            //生成每批次的数据
            List<Long> subList = validQuestionIdList.subList(i , Math.min(i + batchSize, totalQuestionListSize));
            List<QuestionBankQuestion> questionBankQuestions = subList.stream().map(questionId -> {
                QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
                questionBankQuestion.setQuestionBankId(questionBankId);
                questionBankQuestion.setQuestionId(questionId);
                questionBankQuestion.setUserId(loginUser.getId());
                return questionBankQuestion;
            }).collect(Collectors.toList());
            //使用事务处理每批数据
            //获取代理方法,不能直接this进行调用会导致事务失效
            QuestionBankQuestionService questionBankQuestionService = (QuestionBankQuestionServiceImpl) AopContext.currentProxy();

            //异步处理每批数据,将任务添加到异步任务列表
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                questionBankQuestionService.batchAddQuestionsToBankInner(questionBankQuestions);
            }, customExecutor);
            futures.add(future);

            //等待所有批次完成操作
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

            //关闭线程池
            customExecutor.shutdown();
        }
    }

    /**
     * 批量添加题目到题库(内部方法,不对外暴露)
     * @param questionBankQuestions
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchAddQuestionsToBankInner(List<QuestionBankQuestion> questionBankQuestions){
            try {
                //使用Mybatis-plus的批量插入方法批量插入数据
                boolean result = this.saveBatch(questionBankQuestions);
                if (!result){
                    throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目添加到题库失败");
                }
            } catch (DataIntegrityViolationException e) {
                log.error("数据库唯一键冲突或违反其他完整性约束, 错误信息: {}", e.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目已存在于该题库，无法重复添加");
            } catch (DataAccessException e) {
                log.error("数据库连接问题、事务问题等导致操作失败, 错误信息: {}", e.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库操作失败");
            } catch (Exception e) {

                log.error("添加题目到题库时发生未知错误，错误信息: {}", e.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
            }
    }

    /**
     * 批量移除题目到题库(仅管理员可用)
     * @param questionIdList 题目id列表
     * @param questionBankId 题库id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchRemoveQuestionsToBank(List<Long> questionIdList, Long questionBankId) {
        //参数校验
        //检查题目id列表不能为空
        ThrowUtils.throwIf(CollUtil.isEmpty(questionIdList),ErrorCode.PARAMS_ERROR,"题目id列表不能为空");
        //检查题库id不能为负数
        ThrowUtils.throwIf(questionBankId<=0,ErrorCode.PARAMS_ERROR,"题库 id 非法");

        //执行移除题目
        for (Long questionId : questionIdList) {
            //构造查询
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                    //这里使用了Mybatis-plus的提供的方法
                    //.eq是查询条件看题库题目的关联表中的question_id和question_bank_id是否匹配,防止误删
                    .eq(QuestionBankQuestion::getQuestionId,questionId)
                    .eq(QuestionBankQuestion::getQuestionBankId,questionBankId);

            boolean result = this.remove(lambdaQueryWrapper);
            ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"题目移除题库失败");
        }


    }

}
